package com.weijin.web.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 建立连接 接收消息，断开连接
 *
 * @Author WeiJin
 * @Version 1.0
 * @Date 2025/3/18 9:36
 */
@Slf4j
public class ChatHandler extends TextWebSocketHandler {

    Map<String, WebSocketSession> map = new HashMap<>();

    public ChatHandler() {
    }

    /**
     * 建立连接
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        String id = session.getId();
        map.put(id, session);
        log.info("[websocket信息] 建立新的websocket连接：{}", session);
    }

    /**
     * 处理文本消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String id = session.getId();
        String payload = message.getPayload();
        int length = message.getPayloadLength();
        log.info("[websocket信息] 收到session id = {} 的websocket信息：{},内容长度为；{}", id, payload, length);
    }

    /**
     * 断开连接
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String id = session.getId();
        WebSocketSession removeSession = map.remove(id);
        log.info("[websocket信息] 断开连接：{}", removeSession);
    }
}
